from PIL import Image
import math


def merge_images_grid(image_paths, output_path):
    images = [Image.open(img) for img in image_paths]

    # 自动计算网格（例如 2x2）
    n = len(images)

    cols = math.ceil(math.sqrt(n))
    rows = math.ceil(n / cols)

    # # 找出最大宽高（统一尺寸可选）
    # max_width = max(img.width for img in images)
    # max_height = max(img.height for img in images)
    #
    # # 创建画布
    # total_width = max_width * cols
    # total_height = max_height * rows
    # merged = Image.new('RGBA', (total_width, total_height))
    #
    # for idx, img in enumerate(images):
    #     if idx >= rows * cols:
    #         break
    #     row = idx // cols
    #     col = idx % cols
    #     x = col * max_width
    #     y = row * max_height
    #
    #     # 居中粘贴（可选）
    #     x_offset = x + (max_width - img.width) // 2
    #     y_offset = y + (max_height - img.height) // 2
    #     merged.paste(img, (x_offset, y_offset), img)
    #
    # merged.save(output_path)
    # print(f"✅ 网格拼接完成，保存为: {output_path}")


# 使用示例：自动布局
merge_images_grid(['C:\\5\\1B28AA620000.png', 'C:\\5\\1B28AA620001.png', 'C:\\5\\1B28AA620002.png', 'C:\\5\\1B28AA620003.png'], 'merged_grid.png')

# 指定 2 行 3 列
# merge_images_grid(['1.png', '2.png', '3.png'], 'grid.png', grid_size=(2, 3))
